package 线程和TCP网络编程.TAKS2.ServerSocket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerRunnableImpl implements Runnable {

    public Socket socket;

    public ServerRunnableImpl(Socket socket) {
        this.socket = socket;
        //利用构造方法来初始化线程的socket对象
    }

    @Override
    public void run() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //创建字符缓冲输入流读取客户端输入的内容
            while (true) {
                String str = br.readLine();
                //读取用户输入的内容,如果没有输入内容
                //readline就会堵塞线程
                if (str != null) {
                    for (Socket s : ServerTest.socketList) {
                        //遍历list集合,向所有存储的客户端对象发送消息
                        PrintWriter pw = new PrintWriter(s.getOutputStream());
                        pw.println(str);
                        //用输出对象将内容打印出去
                        pw.flush();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
